import { Project } from '@entity/project';
import { FriendInfo, User } from '@entity/user';
import { SystemMsg } from '@entity/system_msg';
import { PrivateMsg } from '@entity/chat';
import { storageMe, storageAllProject, storageAllUser, storageUser, storagePrivateMsg, storageSystemMsg, storageFriend } from './utils/functions';
import { delCache, FIELD, setCache } from './utils/cache';

export default {
    setMe(state: any, me: User): void {
        storageMe(state, me);
    },
    refresh(state: any): void {
        if (state.localify.me != undefined) {
            setCache(FIELD.ME(), state.localify.me, 30);
        }
    },
    logout(state: any): void {
        state.localify.me = undefined;
        state.localify.project_map = undefined;
        state.localify.user_map = undefined;
        state.localify.system_msg_map = undefined;
        state.localify.private_msg_map = undefined;
        state.localify.friend_map = undefined;
        delCache(FIELD.ME());
    },

    addAllProjects(state: any, projects: Array<Project>): void {
        storageAllProject(state, projects);
    },

    addAllUsers(state: any, users: Array<User>): void {
        storageAllUser(state, users);
    },
    addUser(state: any, user: User): void {
        storageUser(state, user);
    },

    async addAllPrivateMsg(state: any, list: Array<PrivateMsg>): Promise<void> {
        for (let index = 0; index < list.length; index++) {
            const element: PrivateMsg = list[index];
            await storagePrivateMsg(state, element);
        }
    },
    addPrivateMsg(state: any, privateMsg: PrivateMsg): void {
        storagePrivateMsg(state, privateMsg);
    },

    addAllSystemMsg(state: any, msgList: Array<SystemMsg>): void {
        msgList.forEach((msg: SystemMsg) => {
            storageSystemMsg(state, msg);
        })
    },
    addSystemMsg(state: any, systemMsg: SystemMsg): void {
        storageSystemMsg(state, systemMsg);
    },

    addAllFriendInfo(state: any, friendInfos: Array<FriendInfo>): void {
        friendInfos.forEach((info: FriendInfo) => {
            console.log(info);
            storageFriend(state, info);
        })
    },
    addFriendInfo(state: any, friendInfo: FriendInfo): void {
        storageFriend(state, friendInfo);
    },
}